package com.server.modules.api.service;

import com.lowagie.text.pdf.codec.Base64;
import com.server.common.utils.*;
import com.server.modules.api.dao.MemberAPIDao;
import com.server.modules.api.dao.TagAPIDao;
import com.server.modules.api.vo.MemberVo;
import com.server.modules.api.vo.PaymentVO;
import com.server.modules.sys.entity.User;
import com.server.modules.sys.entity.charge.ChargeRecord;
import com.server.modules.sys.entity.member.Member;
import com.server.modules.sys.entity.tag.Tag;
import com.server.modules.sys.service.member.MemberService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

/**
 * Author Administrator
 * Date 2016/7/25
 */
@Service
public class MemberAPIService extends MemberService {

	@Resource
	private IMService imService;

	@Resource
	MemberAPIDao memberAPIDao;

	@Resource
	TagAPIDao tagAPIDao;
	/**
	 * 普通用户注册
	 *
	 * @param member
	 * @return
	 */
	@Transactional(readOnly = false)
	public Member insertMember(Member member) {
		String password = member.getPassword();
		try {
			//给密码加密
			member.setPassword(MD5Utils.getMd5Password(member.getPassword(),member.getPassword()));
			member.setIsNewRecord(true);
		} catch (Exception e) {
			e.printStackTrace();
		}
		save(member);
		member.setPassword(password);
		return setlectMemberForLogin(member);
	}

	/**
	 * 普通用户登录
	 *
	 * @param member
	 * @return
	 */
	@Transactional(readOnly = false)
	public Member setlectMemberForLogin(Member member) {
		try {
			Member example = new Member();
			example.setTelephone(member.getTelephone());
			example.setPassword(MD5Utils.getMd5Password(member.getPassword(),member.getPassword()));

			Member result = memberAPIDao.login(example);
			if (result != null) {
				result.setLoginTime(member.getLoginTime());
				result.setLoginIp(member.getLoginIp());
				result.setDeviceType(member.getDeviceType());
				result.setVersion(member.getVersion());
				result.setDeviceId(member.getDeviceId());
				result.setSessionId(UUIDUtils.getUUID());
				save(result);
				JedisUtils.set(result.getId(),result.getSessionId(),0);
				return selectMemberById(result.getId());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public Member selectMemberByTelephone(String telephone) {
		Member member = new Member();
		member.setTelephone(telephone);

		return memberAPIDao.selectByTelephone(member);
	}

	public Member selectMemberBySessionId(String sessionId) {
		Member member = new Member();
		member.setSessionId(sessionId);

		return memberAPIDao.selectBySessionId(member);
	}

	public Member selectMemberById(String id) {
		return get(id);
	}

	@Transactional(readOnly = false)
	public Member selectMemberByUnionId(Member member) {
		Member result = memberAPIDao.loginByWx(member);
		if (result != null && !StringUtils.isEmpty(result.getTelephone()) && result.getTelephone().matches("1[3,4,5,7,8]\\d{9}")) {
			result.setUnionId(member.getUnionId());
			return updateOfLogin(member, result);
		}
		return null;
	}

	public Member getMemberByUnionId(Member member){
		return memberAPIDao.loginByWx(member);
	}
	@Transactional(readOnly = false)
	public Member selectMemberByOpenId(Member member) {
		Member result = memberAPIDao.loginByQq(member);
		if (result != null && !StringUtils.isEmpty(result.getTelephone()) && result.getTelephone().matches("1[3,4,5,7,8]]\\d{9}")) {
			result.setOpenId(member.getOpenId());
			return updateOfLogin(member, result);
		}
		return null;
	}

	public Member selectMemberByPassword(Member member) {
		try {
			member.setPassword(MD5Utils.getMd5Password(member.getPassword(),member.getPassword()));
		} catch (Exception e) {
			return null;
		}
		return memberAPIDao.selectByPassword(member);
	}

	@Transactional(readOnly = false)
	public Member updatePassword(Member member) {
		try {
			member.setPassword(MD5Utils.getMd5Password(member.getPassword(),member.getPassword()));
		} catch (Exception e) {
		}
		memberAPIDao.updatePassword(member);

		//修改环信服务器中的用户密码
		Map<String, String> data = new HashMap<String, String>();
		data.put("newpassword", UUIDUtils.getUUID() + UUIDUtils.getUUID());
		imService.modifyIMUserPasswordWithAdminToken(member.getHxUsername(), data);

		return selectMemberByPassword(member);
	}

	/**
	 * 登录成功后更新登录信息
	 *
	 * @param member 原始用户信息
	 * @param result 新的用户信息
	 * @return
	 */
	@Transactional(readOnly = false)
	private Member updateOfLogin(Member member, Member result) {
		if (result != null) {
			//说明查询到用户信息，需要更新用户信息
			setFace(result);
			result.setAccessToken(member.getAccessToken());
			//更新昵称
			if (!StringUtils.isEmpty(member.getNickname())) {
				result.setNickname(member.getNickname());
			}
//			if (!StringUtils.isEmpty(member.getNativeProvince())) {
//				result.setNativeProvince(member.getNativeProvince());
//			}
//			if (!StringUtils.isEmpty(member.getNativeCity())) {
//				result.setNativeCity(member.getNativeCity());
//			}
//			if (!StringUtils.isEmpty(member.getResidentProvince())) {
//				result.setResidentProvince(member.getResidentProvince());
//			}
//			if (!StringUtils.isEmpty(member.getResidentCity())) {
//				result.setResidentCity(member.getResidentCity());
//			}
			result.setLoginTime(member.getLoginTime());
			result.setLoginIp(member.getLoginIp());
			result.setDeviceType(member.getDeviceType());
			result.setVersion(member.getVersion());
			result.setDeviceId(member.getDeviceId());
			result.setSessionId(UUIDUtils.getUUID());
			JedisUtils.set(result.getId(),result.getSessionId(),0);//将用户信息放入缓存
			save(result);
			return selectMemberById(result.getId());
		}
		return member;
	}
	public void setFace(Member member) {
		if (!StringUtils.isEmpty(member.getFace())) {
			//如果有头像链接，就下载头像并将新地址设置给头像变量
			try {
				Properties prop = PathUtils.getProperties("application.properties");
				String path = HttpUtils.downLoadImage(member.getFace());
				member.setFace(prop.get("imagePath") + path);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	public List<Tag> findTagsList(Member member) {
			return tagAPIDao.selectTagsByMember(member);
	}

	public Member getMemberByPhoneNum(String phoneNum){
		return memberAPIDao.getMemberByPhoneNum(phoneNum);
	}

	public List<ChargeRecord> getChargeRecordList(PaymentVO paymentVO){
		return memberAPIDao.getChargeRecordList(paymentVO);
	}

}
